package com.hy.logtrace.interceptor;

import com.hy.logtrace.config.LogTraceProperties;
import com.hy.logtrace.util.TraceIdContext;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class LogTraceInterceptor implements HandlerInterceptor {
    private LogTraceProperties logTraceProperties = null;
    private String traceKey = null;

    public LogTraceInterceptor(LogTraceProperties logTraceProperties) {
        this.traceKey = logTraceProperties.getTraceKey();
        this.logTraceProperties = logTraceProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 没有开启 trace 功能，直接返回
        if (!logTraceProperties.isEnable()) {
            return true;
        }

        // 生成一个traceId
        // 如果请求头中已经有 traceId，则使用它；否则生成新的 traceId
        String traceId = request.getHeader(traceKey);
        if (traceId == null || traceId.isEmpty()) {
            traceId = TraceIdContext.generateTraceId();
        }

        // 设置 traceId 到上下文中
        TraceIdContext.setTraceId(traceId);
        // 将 traceId 添加到响应头中
        request.setAttribute(this.traceKey, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TraceIdContext.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
